package cc.shacocloud.redis.study.lock.impl;

import cc.shacocloud.redis.study.util.codeBlock.CodeBlockMD;
import cc.shacocloud.redis.study.util.codeBlock.CodeBlockMDManage;
import cc.shacocloud.redis.study.util.redis.RedisUtil;
import cc.shacocloud.redis.study.lock.OptimisticLock;
import redis.clients.jedis.BuilderFactory;

/**
 * 基于redis 实现的乐观锁
 */
@CodeBlockMD(mdDirPath = "/redis/lock", mdFileName = "optimisticLock")
public class RedisOptimisticLock implements OptimisticLock {

    @Override
    public int getLockVersion(String lockName) {
        String script = CodeBlockMDManage.get(RedisOptimisticLock.class, "getLockVersion");
        return RedisUtil.eval(BuilderFactory.LONG, script, 1, lockName).intValue();
    }

    @Override
    public boolean submitLock(String lockName, int version) {
        String script = CodeBlockMDManage.get(RedisOptimisticLock.class, "submitLock");
        return RedisUtil.eval(BuilderFactory.BOOLEAN, script, 1, lockName, String.valueOf(version));
    }

}
